class Question
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  belongs_to :question_list
  field :content, type: String

  has_one :topic, autobuild: true, dependent: :destroy, as: :topic_container
  # belongs_to :question_type

  has_many :question_versions, order: :created_at.asc, dependent: :destroy do
    def history
      where(:id.ne => last.id)
    end
  end

  field :removed_by, type: Moped::BSON::ObjectId # of User
  field :removed_at, type: Time
  
  def set_question_list(value)
    self.question_list = value
  end

  def current_version
    if @current_version.nil?
      d = self.question_versions.sort.last
      if d.nil?
        d = QuestionVersion.new(question: self, author: self.question_list.author, 
            question_type: self.question_list.section.default_question_type )
      end
      @current_version = d
    else
      @current_version
    end
  end

  def question_type
    self.current_version.question_type
  end

  def question_type_id
    question_type.id
  end

  def question_type=(value)
    self.current_version.question_type = value
  end

  # after_save do |doc|
  #   if !doc.question_list.published
  #     doc.current_version.save
  #   end
  # end

  def commit_suggestion(qv)
    qv.question = self
    qv.save
    self.current_version.vote.save if self.question_list.vote
  end

  after_create do |doc|
    self.current_version.vote.save if self.question_list.vote
    self.topic.save
  end

  def last_question
    q = Question.where(:id.in => self.question_list.question_ids,
      :created_at.lt => self.created_at).last
    if block_given?
      yield(q) if q.present?
    else
      q
    end
  end
  def next_question
    q = Question.where(:id.in => self.question_list.question_ids,
      :created_at.gt => self.created_at).first
    if block_given?
      yield(q) if q.present?
    else
      q
    end
  end
  def position
    Question.where(:id.in => self.question_list.question_ids,
      :created_at.lt => self.created_at).count + 1
  end
end
